<template>
    <div>
        <!-- <el-button type="primary" size="mini" style="float:right;margin:4px 0" @click="layoutDialog = true">页面布局</el-button> -->

        <vxe-table
            :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
            :data="tableData"
            :key="tableKey + 'tableKey'"
            v-loading="loading"
            border
            stripe
            resizable
            :auto-resize="true"
            :sort-config="{
                defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                remote: true,
            }"
            highlight-current-row
            @sort-change="changeTableSort"
            :resizable-config="{ minWidth: '60' }"
            ref="table"
            show-header-overflow="tooltip"
            show-footer-overflow="tooltip"
            header-align="center"
        >
            <vxe-column
                v-for="item in showFieldList"
                :field="item.id"
                :title="item.content"
                :key="item.content"
                :align="getAlign(item)"
                :min-width="item.minWidth || '105px'"
                show-overflow="tooltip"
                sortable
            >
                <template slot-scope="scope">
                    <span v-if="formatParam.includes(item.id)" style="float:right">
                        {{ numberFormat(scope.row[item.id], 2) || '--' }}
                    </span>
                    <span v-else-if="['hgDate', 'redeemLawdate', 'redeemLiquidate', 'settleDate'].includes(item.id)">
                        {{ dateFormat(scope.row[item.id]) || '--' }}
                    </span>
                    <span v-else>
                        {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                    </span>
                </template>
            </vxe-column>
        </vxe-table>

        <risk-pagination :paging="page" @page-change="pageRet"></risk-pagination>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :reset-no-selected-field-list="resetNoSelectedFieldList"
            table-name="TN_BANK_ONWAY_HG"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat } from '@/utils/tools';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({ name: 'BankOnWayHg', components: { RiskTableLayout, RiskPagination } })
export default class BankOnWayHg extends Vue {
    @Prop()
    transData: any;

    resetNoSelectedFieldList = [
        { id: 'fundId', content: ' 产品序号' },
        { id: 'fundCode', content: '产品编码' },
        { id: 'fundName', content: '产品名称' },
    ];
    numberFormat = numberFormat;
    dateFormat = dateFormat;

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [{ id: 'stockCode', content: '证券回购代码', minWidth: '130px', align: 'left' }];

    tableData: any[] = []; // 表格数据

    tableKey: number = -1;

    loading: boolean = false; // 页面渲染

    private sortProp: string = 'stockCode'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'VC_INTER_CODE ASC'; // 默认排序字段

    private page: pages = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    formatParam = [
        'dealBalance',
        'dealPrice',
        'redeemInterest',
        'nowInterest',
        'originalBalance',
        'backBalance',
        'penaltyInterest',
        'endDealBalance',
    ];

    tableColumns = [
        { id: 'fundId', content: ' 产品序号', align: 'left' },
        { id: 'fundCode', content: '产品编码', align: 'left' },
        { id: 'fundName', content: '产品名称', align: 'left' },
        { id: 'assetId', content: '资产单元编号', minWidth: '130px', align: 'left' },
        { id: 'assetName', content: '资产单元名称', minWidth: '130px', align: 'left' },
        { id: 'basecombiId', content: '组合编码', align: 'left' },
        { id: 'combiName', content: '组合名称', align: 'left' },
        { id: 'stockCode', content: '证券回购代码', minWidth: '130px', align: 'left' },
        { id: 'stockNameSt', content: '证券名称', align: 'left' },
        { id: 'stockType', content: '证券类别', align: 'center' },
        { id: 'entrustDirection', content: '委托方向', align: 'center' },
        { id: 'rivalCode', content: '交易对手编码', minWidth: '130px', align: 'left' },
        { id: 'allName', content: '交易对手名称', minWidth: '130px', align: 'left' },
        { id: 'hgDate', content: '首期回购日期', minWidth: '130px', align: 'center' },
        { id: 'redeemLawdate', content: '法定购回日期', minWidth: '130px', align: 'center' },
        { id: 'redeemLiquidate', content: '实际购回日期', minWidth: '130px', align: 'center' },
        { id: 'settleSpeed', content: '清算速度' },
        { id: 'settleDate', content: '购回交割日期', minWidth: '130px', align: 'center' },
        { id: 'redeemDays', content: '回购天数' },
        { id: 'actualDays', content: '实际占款天数', minWidth: '130px' },
        { id: 'yearDays', content: '计息天数' },
        { id: 'dealBalance', content: '首期成交金额', minWidth: '140px' },
        { id: 'dealPrice', content: '回购利率(%)', minWidth: '140px' },
        { id: 'redeemInterest', content: '回购利息' },
        { id: 'endDealBalance', content: '到期成交金额', minWidth: '130px' },
        { id: 'nowInterest', content: '计提利息', minWidth: '160px' },
        { id: 'originalBalance', content: '原合同金额', minWidth: '120px' },
        { id: 'backBalance', content: '提前购回金额', minWidth: '130px' },
        { id: 'currentContactBalance', content: '当前合同金额', minWidth: '130px' },
        { id: 'penaltyInterest', content: '罚息' },
    ];

    // 排序字段
    sortableObj = {
        fundId: 'L_FUND_ID',
        fundCode: 'VC_FUND_CODE',
        fundName: 'VC_FUND_NAME',
        assetId: 'L_ASSET_ID',
        assetName: 'VC_ASSET_NAME',
        basecombiId: 'L_BASECOMBI_ID',
        combiName: 'VC_COMBI_NAME',
        stockCode: 'VC_INTER_CODE',
        stockNameSt: 'VC_STOCK_NAME',
        stockType: 'C_STOCK_TYPE',
        entrustDirection: 'C_ENTRUST_DIRECTION_CODE',
        rivalCode: 'VC_RIVAL_CODE',
        allName: 'VC_ALL_NAME',
        hgDate: 'L_HG_DATE',
        redeemLawdate: 'L_REDEEM_LAWDATE',
        redeemLiquidate: 'L_REDEEM_LIQUIDATE',
        settleSpeed: 'L_SETTLE_SPEED',
        settleDate: 'L_SETTLE_DATE',
        redeemDays: 'L_REDEEM_DAYS',
        yearDays: 'L_YEAR_DAYS',
        dealBalance: 'EN_DEAL_BALANCE',
        dealPrice: 'EN_DEAL_PRICE',
        redeemInterest: 'EN_REDEEM_INTEREST',
        nowInterest: 'EN_NOW_INTEREST',
        originalBalance: 'EN_ORIGINAL_BALANCE',
        backBalance: 'EN_BACK_BALANCE',
        penaltyInterest: 'EN_PENALTY_INTEREST',
        actualDays: 'actualDays',
        endDealBalance: 'endDealBalance',
        currentContactBalance: 'currentContactBalance',
    };

    isFirst: boolean = true; // 是否第一次

    currentRecord: any = {};
    @Watch('transData', { immediate: true, deep: true })
    async handleTab(nowVal, oldVal) {
        if (nowVal['activeTab'] == 'BankOnWayHg') {
            this.layoutDialog = nowVal.detailLayoutDialog;
            if (this.isFirst) {
                await this.queryLayout();
                this.getBankOnWayHgTableData();
                this.isFirst = false;
            } else if (
                !oldVal ||
                JSON.stringify(oldVal.clickRow) !== JSON.stringify(nowVal.clickRow) ||
                JSON.stringify(nowVal.clickRow) !== JSON.stringify(this.currentRecord)
            ) {
                // nowVal['activeTab'] != oldVal['activeTab'] && (await this.queryLayout());
                console.log('BankOnWayHg2');
                this.getBankOnWayHgTableData();
            }
            this.currentRecord = JSON.parse(JSON.stringify(nowVal.clickRow));
        }
    }

    @Watch('layoutDialog')
    handleLayoutDialog() {
        this.$emit('layout-handle', this.layoutDialog);
    }

    pageRet() {
        this.getBankOnWayHgTableData();
    }

    getBankOnWayHgTableData() {
        if (JSON.stringify(this.transData.clickRow) == '{}') {
            return;
        }
        this.loading = true;
        this.$axios
            .post('/productSelect/bankOnWayHg', {
                paging: this.page,
                sort: this.sort,
                productCode: this.transData.clickRow.fundCode,
                productSerialNo: this.transData.clickRow.fundId,
            })
            .then((res: any) => {
                this.tableData = res.list;
                this.page.total = res.total;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 分页
    pageChange(curPage: number) {
        this.page.currentPage = curPage;
        this.getBankOnWayHgTableData();
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_BANK_ONWAY_HG')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            const keys = this.resetNoSelectedFieldList.map(item => item.id);
            this.showFieldList = this.tableColumns.filter(item => !keys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
            } else {
                this.showFieldList = this.fixedFieldList.concat(JSON.parse(resList));
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }
        const fixKeys = this.fixedFieldList.map(item => item.id);
        this.selectedFieldList = this.showFieldList.filter(item => !fixKeys.includes(item.id));
        this.tableKey++;
    }

    // beforeUpdate() {
    //     this.$nextTick(() => {
    //         // 在数据加载完，重新渲染表格
    //         (this.$refs['table'] as any).doLayout();
    //     });
    // }
    getAlign(ele) {
        let obj = this.tableColumns.find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped></style>
